package com.ycz.algorithm.utils.stack;

import com.ycz.algorithm.utils.linkedlist.ListNode;

/**
 * @Description 基于链表实现的栈
 * @ClassName LinkedListStack
 * @Author yanchengzhi
 * @date 2024.11.20 23:33
 */
public class LinkedListStack {

    private ListNode stackPeek; // 头节点作为栈顶

    private int stackSize = 0; // 栈深度

    public LinkedListStack() {
        stackPeek = null;
    }

    // 获取栈深度
    public int size() {
        return stackSize;
    }

    // 判断栈空
    public boolean isEmpty() {
        return size() == 0;
    }

    // 入栈
    public void push(int num) {
        ListNode node = new ListNode(num);
        node.next = stackPeek;
        stackPeek = node;
        stackSize++;
    }

    // 出栈
    public int pop() {
        int num = peek();
        stackPeek = stackPeek.next;
        stackSize--;
        return num;
    }

    // 访问栈顶元素
    public int peek() {
        if (isEmpty()) {
            throw new IndexOutOfBoundsException("栈空无法出栈！");
        }
        return stackPeek.val;
    }

    // 转为数组
    public int[] toArray() {
        ListNode node = stackPeek;
        int[] res = new int[size()];
        for (int i = res.length - 1; i >= 0; i--) {
            res[i] = node.val;
            node = node.next;
        }
        return res;
    }

    public static void main(String[] args) {
        // 初始化栈
        LinkedListStack linkedListStack = new LinkedListStack();
        // 入栈
        linkedListStack.push(1);
        linkedListStack.push(2);
        linkedListStack.push(3);
        int[] res = linkedListStack.toArray();
        commonPrint(res);
        System.out.println("栈顶元素：" + linkedListStack.peek());
        System.out.println("是否栈空？" + linkedListStack.isEmpty());
        System.out.println("栈深度：" + linkedListStack.size());
        // 出栈
        int num = linkedListStack.pop();
        System.out.println("出栈元素：" + num);
        commonPrint(linkedListStack.toArray());
    }

    private static void commonPrint(int[] res) {
        for (int i : res) {
            System.out.print(i + "\t");
        }
        System.out.println();
    }

}
